import type { PayloadAction } from "@reduxjs/toolkit"
import { createSelector, createSlice } from "@reduxjs/toolkit"

import type { Locale, UserInfo, UserState } from "@/interface/user/user"
import { MenuItem } from "@/interface/user/user"
import { decryptData } from "@/utils/encrypt"
import { getGlobalState } from "@/utils/getGloabal"
export const USER_KEY = "user"

const initialState: UserState = {
	...getGlobalState(),
	noticeCount: 0,
	notices: {},
	locale: (localStorage.getItem("locale")! || "en_US") as unknown as Locale,
	menus: [] as MenuItem[],
	permissions: [] as string[],
	userInfo: localStorage.getItem("u1") ? JSON.parse(decryptData(localStorage.getItem("u1"))) : ({} as UserInfo),
	nickName: localStorage.getItem("nickName") || "",
	username: localStorage.getItem("username") || "",
	token: localStorage.getItem("t") || "",
	menuList: [],
	menuData: [],
	logged: false,
	role: "guest",
	newUser: false
}

const userSlice = createSlice({
	name: USER_KEY,
	initialState,
	reducers: {
		reset: () => initialState,
		setUserItem: (state, action: PayloadAction<Partial<UserState>>) => ({ ...state, ...action.payload }),
		setPermissions: (state, action: PayloadAction<Partial<UserState>>) => ({
			...state,
			...action.payload
		}),
		setToken: (state, action: PayloadAction<Partial<UserState>>) => ({
			...state,
			...action.payload
		}),
		setNotices: (state, action: PayloadAction<Partial<UserState>>) => ({
			...state,
			...action.payload
		})
	}
})

export const { reset, setUserItem, setPermissions, setToken } = userSlice.actions

export const userState = (rootState: { [USER_KEY]: UserState }): UserState => {
	return rootState[USER_KEY]
}

export const isZk = createSelector(userState, (state: UserState) => state.userInfo.merchantId === "0")
export const merchantId = createSelector(userState, (state: UserState) => state.userInfo.merchantId)
export const userLoginName = createSelector(userState, (state: UserState) => state.userInfo.username)

export default userSlice.reducer
